package com.gxgeek.fastdfsweb.service;

import com.fast.pool.FastdfsPool;
import com.fast.pool.StorageClient;
import com.gxgeek.fastdfsweb.dto.FastDFSFile;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.NameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author gaoxing
 * @create 2017-11-28 下午4:39
 */
@Service
@Slf4j
public class FastdfsUtil {

    @Autowired
    private FastdfsPool pool;

    public String[] upload(FastDFSFile file, NameValuePair[] valuePairs) throws Exception {
        StorageClient storageClient = null;
        String[] uploadResults = null;
        try {
            storageClient = pool.getResource();
            uploadResults = storageClient.upload_file(file.getContent(), file.getSuffix(), valuePairs);

        } catch (Exception e1) {
            log.error(e1.getMessage(),e1);
            pool.returnResource(storageClient);
        } finally {
            pool.returnResource(storageClient);
        }
        return uploadResults;// getFileUrl(uploadResults);
    }


    /**
     * 上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    public String[] upload(FastDFSFile file) throws Exception {
        return upload(file, null);
    }


    public byte[] downloadFile(String groupName, String remoteFileName) throws Exception {
        StorageClient storageClient = null;
        byte[] downloadResults = null;
        try {
            storageClient = pool.getResource();
            downloadResults = storageClient.download_file(groupName, remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            pool.returnResource(storageClient);
        }
        return downloadResults;
    }

}
